# TODO: 导入必要的库和模块
import matplotlib.pyplot as plt
import pickle
from sklearn.preprocessing import MinMaxScaler
from sklearn.datasets import load_digits
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from tqdm import tqdm
# TODO: 加载数字数据集
digits = load_digits()

#特征缩放
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(digits.data)

# TODO: 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, digits.target, test_size=0.2, random_state=42)

# TODO: 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_accuracy = 0
best_k = 1
best_knn_model = None

# TODO: 初始化一个列表以存储每个k值的准确率
accuracies = []
k_values = []

# TODO: 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
for k in tqdm(range(1, 41), desc='Training KNN models'):
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)

    # 保存准确率
    accuracies.append(accuracy)
    k_values.append(k)
    
    # 更新最佳模型
    if accuracy > best_accuracy:
        best_accuracy = accuracy
        best_k = k
        best_knn_model = knn

# TODO: 将最佳KNN模型保存到二进制文件
with open ("best_knn_model.pkl" , 'wb') as f:
    pickle.dump(best_knn_model,f)

# TODO: 打印最佳准确率和相应的k值 
print(f"Best accuracy: {best_accuracy} with k={best_k}")

# 保存图表为PDF
# 绘制图表
plt.figure(figsize=(10, 6))
plt.plot(k_values, accuracies, marker='o', label='Accuracy')
plt.axvline(x=best_k, color='r', linestyle='--', label=f'Best k={best_k}')
plt.scatter(best_k, best_accuracy, color='r')
plt.text(best_k, best_accuracy, f' ({best_k}, {best_accuracy:.2f})', color='r')
plt.xlabel('k value')
plt.ylabel('Accuracy')
plt.title('KNN Varying number of Neighbors')
plt.legend()
plt.grid(True)

# 保存图表为PDF
plt.savefig('accuracy_plot.pdf', bbox_inches='tight')
plt.show()


